﻿using System;
using System.Threading;

using Sunyi.Project.WebPoint.BusinessLogic;
using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.DataContract;

namespace Sunyi.Project.WebPoint.WebControl
{
    public abstract class WebPointPage : System.Web.UI.Page
    {
        PermissionManager permissionManager;
        protected PermissionManager PermissionManager
        {
            get
            {
                if (permissionManager == null) permissionManager = new PermissionManager();

                return permissionManager;
            }
        }

        protected virtual PermissionType DefaultPermissionType
        {
            get
            {
                return PermissionType.Read;
            }
        }

        public PermissionType RequestPermissionType
        {
            get
            {
                PermissionType requestPermissionType;

                if (!string.IsNullOrEmpty(Request.Params[WebControlCommon.PermissionType]))
                {
                    requestPermissionType = (PermissionType)Enum.Parse(typeof(PermissionType), Request.Params[WebControlCommon.PermissionType], true);
                }
                else
                {
                    requestPermissionType = PermissionType.Read;
                }

                return requestPermissionType;
            }
        }

        public User CurrentUser
        {
            get
            {
                return Session[WebPointGlobalConstant.Session_CurrentUser] as User;
            }
        }

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);

            if (EnvironmentSetting.IsDebugMode)
            {
                if (Session[WebPointGlobalConstant.Session_CurrentUser] == null)
                {
                    UserManager userManager = new UserManager();
                    var developerAccount = userManager.SelectByName(WebPointGlobalConstant.DeveloperAccount);
                    if (developerAccount != null) Session[WebPointGlobalConstant.Session_CurrentUser] = developerAccount;
                }
            }

            if (!this.PermissionCheck())
            {
                Session.Clear();

                Response.Redirect(EnvironmentSetting.LoginPageUrl + "?ReturnUrl=" + Request.Url.ToString());
            }

            if (this.CurrentUser != null)
            {
                Thread.CurrentThread.Name = this.CurrentUser.UserName;
            }
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);

            ApplyPermission();

            #region Write Audit Log for Read Leave

            string requestString = Request.Path;
            if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
            {
                requestString += WebPointGlobalConstant.QuestionMark + Request.QueryString.ToString();
            }

            AuditLogger.Write(AuditLogOperationCode.Read, this.GetType().Name, requestString);

            #endregion
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);

            // Analyze page and save test information to database.
            if (!string.IsNullOrEmpty(Request.Params[WebPointGlobalConstant.AnalyzePage]))
            {
                PageAnalyzer.Analyze(this);
            }
        }

        protected void ShowClientMessage(string message)
        {
            WebControlCommon.ShowClientMessage(this, message);
        }

        protected void ClientRedirect(string url)
        {
            WebControlCommon.ClientRedirect(this, url);
        }

        protected void CloseClientWindow()
        {
            WebControlCommon.CloseClientWindow(this);
        }

        protected virtual bool PermissionCheck()
        {
            bool flag = false;

            if (this.CurrentUser != null)
            {
                flag = HasPermission(this.DefaultPermissionType);

                if (flag && this.RequestPermissionType != this.DefaultPermissionType)
                {
                    flag = HasPermission(this.RequestPermissionType);
                }
            }

            return flag;
        }

        protected bool HasPermission(PermissionType permissionType)
        {
            return this.PermissionManager.HasPermission(Request.Path, this.CurrentUser, permissionType);
        }

        protected bool IsRoleOnly(string roleName)
        {
            bool flag = false;

            if (this.CurrentUser.Roles.Count == 1)
            {
                RoleManager roleManager = new RoleManager();
                Role role = roleManager.Select(this.CurrentUser.Roles[0]);
                if (role != null && role.RoleName == roleName)
                {
                    flag = true;
                }
            }

            return flag;
        }

        protected virtual void ApplyPermission() { }
    }
}